package com.c.ctgproject.ui.collect

import android.graphics.Color
import android.view.animation.AnimationUtils
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import com.c.ctgproject.R
import com.c.ctgproject.adapter.CommonMenuAdapter
import com.c.ctgproject.base.BaseActivityV2
import com.c.ctgproject.base.CTGproject
import com.c.ctgproject.databinding.ActivityCollectCarBinding
import com.c.ctgproject.entity.MenuBeanV2
import com.c.ctgproject.entity.guang.UserMenuEntity
import com.c.ctgproject.http.ApiMethods
import com.c.ctgproject.http.MyObserverHandlerLoading
import com.c.ctgproject.ui.collect.check.CreatePassCheckActivity
import com.c.ctgproject.ui.collect.check.OutCheckActivity
import com.c.ctgproject.ui.collect.check.PassCheckActivity
import com.c.ctgproject.ui.login.LoginActivity
import com.c.ctgproject.ui.login.LoginViewModel
import com.c.ctgproject.ui.other.SettingActivity
import com.c.ctgproject.utils.*
import com.c.ctgproject.wiget.dialog.UpdateDialog
import com.tencent.bugly.crashreport.CrashReport
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.textColor
import org.jetbrains.anko.textColorResource
import org.json.JSONObject

/**
 *作者:LiBW
 *创建日期: 2021/9/7
 *描述:广汽首页
 */
class CollectCarHomeActivity : BaseActivityV2() {
    private val mBinding by lazy { ActivityCollectCarBinding.inflate(layoutInflater) }
    override fun getLayout() = mBinding.root
    private val loginViewModel: LoginViewModel by lazy { ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory(application))[LoginViewModel::class.java] }
    private val mList = ArrayList<MenuBeanV2>()
    private val mAdapter by lazy { CommonMenuAdapter(this, mList) }
    private var mMenuList = ArrayList<String>()
    override fun event() {
        //判断app更新
        var versionName = this@CollectCarHomeActivity.packageManager.getPackageInfo(this@CollectCarHomeActivity.packageName, 0).versionName
        versionName = "v$versionName"
        loginViewModel.checkUpdate(versionName)
        mBinding.mMenuRV.adapter = mAdapter
        mBinding.mMenuRV.layoutManager = GridLayoutManager(this, 2, GridLayoutManager.VERTICAL, false)
        ApiMethods.apiSubscribe(ApiMethods.retrofit.getUserMenu(), MyObserverHandlerLoading(this, loading) {
            MyLog.d("菜单回调:$it")
            val data = getGson().fromJson(it, UserMenuEntity::class.java).data
            if(data.isNullOrEmpty()){
                //该token有毛病置空
                userToken=""
                startActivity<LoginActivity>()
                finish()
            }else{
                data?.let { list ->
                    list.forEach { bean ->
                        mMenuList.add(bean.menuCode.handlerNull())
                    }
                    menuCar()
                }
            }

        })
        //版本检查回调更新
        loginViewModel.updateEntity.observe(this, Observer { entity ->
            if (entity == null) return@Observer
            if (entity.status == 1) {
                //判定更新
                when (entity.data?.forceUpdate) {
                    null -> {
                        //当前是最新版本 进行token登录

                    }
                    "1" -> {
                        UpdateDialog(this@CollectCarHomeActivity, R.style.MillionDialogStyle, entity.data?.versionUrl.handlerNull()).show()
                    }
                    "0" -> {
                        if (!CTGproject.getBaseApplication().isDownloadApk) {
                            //修复更新
                            AlertDialog.Builder(this@CollectCarHomeActivity)
                                .setCancelable(false)
                                .setTitle("更新")
                                .setMessage(entity.data?.versionDesc)
                                .setPositiveButton("下载安装") { _, _ ->
                                    UpdateDialog(this@CollectCarHomeActivity, R.style.MillionDialogStyle, entity.data?.versionUrl.handlerNull()).show()
                                }
                                .setNegativeButton("取消") { _, _ ->
                                    //取消非自动更新 进行自动登录
                                }.show()
                        }
                    }

                }
            } else {
                CustomToast.showToast(this@CollectCarHomeActivity, entity.msg.handlerNull())
            }
        })
    }

    private val perPoint = HashMap<String, Int?>()

    override fun onResume() {
        super.onResume()
        when (prePosition) {
            0 -> {
                menuCar()
            }
            1 -> {
                menuBattery()
            }
            2 -> {
                menuPart()
            }
            3 -> {
                menuMaterial()
            }
            4 -> {
                menuCheck()
            }
        }
    }

    private fun menuCar() {
        mBinding.mTitleText.text = "报废车"
        mList.clear()
        if ("car_pre_input" in mMenuList) mList.add(MenuBeanV2("车辆信息预录入", R.mipmap.a, PreInputCarInfoActivity::class.java))
        if ("car_ware_in" in mMenuList) mList.add(MenuBeanV2("登记入库", R.mipmap.b, CarListActivity::class.java, perPoint["car_ware_in"]))
        if ("car_pound" in mMenuList) mList.add(MenuBeanV2("车辆过磅", R.mipmap.c, CarListActivity::class.java, perPoint["car_pound"]))
        if ("car_check" in mMenuList) mList.add(MenuBeanV2("车辆初检", R.mipmap.f, CarListActivity::class.java, perPoint["car_check"]))
        if ("car_pretreatment" in mMenuList) mList.add(MenuBeanV2("车辆预处理", R.mipmap.e, CarListActivity::class.java, perPoint["car_pretreatment"]))
        if ("car_dismantle_create" in mMenuList) mList.add(MenuBeanV2("新建拆解单", R.mipmap.d, CarCanHandlerListActivity::class.java, perPoint["car_dismantle_create"]))
        if ("car_dismantle_list" in mMenuList) mList.add(MenuBeanV2("拆解单列表", R.mipmap.h, CarHandlerOverListActivity::class.java, perPoint["car_dismantle_list"]))
        if ("car_destruction_photo" in mMenuList) mList.add(MenuBeanV2("毁型拍照", R.mipmap.g, DestroyTypeActivity::class.java, perPoint["car_destruction_photo"]))
        if ("car_search_app" in mMenuList) mList.add(MenuBeanV2("车辆查询", R.mipmap.gg, CarSearchActivity::class.java))

        mAdapter.notifyDataSetChanged()


        ApiMethods.apiSubscribe(ApiMethods.retrofit.getPointCar(), MyObserverHandlerLoading(this) {
            MyLog.d("回调:$it")
            val json = JSONObject(it)
            val data = json.getJSONObject("data")
            mList.forEach { bean ->
                when (bean.name) {
                    "登记入库" -> {
                        bean.count = data.optInt("entrance", 0)
                        perPoint["car_ware_in"] = bean.count
                    }
                    "车辆过磅" -> {
                        bean.count = data.optInt("pound", 0)
                        perPoint["car_pound"] = bean.count
                    }
                    "车辆初检" -> {
                        bean.count = data.optInt("carCheck", 0)
                        perPoint["car_check"] = bean.count
                    }
                    "车辆预处理" -> {
                        bean.count = data.optInt("pretreatment", 0)
                        perPoint["car_pretreatment"] = bean.count
                    }
                    "新建拆解单" -> {
                        bean.count = data.optInt("detachable", 0)
                        perPoint["car_dismantle_create"] = bean.count
                    }
                    "拆解单列表" -> {
                        bean.count = data.optInt("carDismantleOrder", 0)
                        perPoint["car_dismantle_list"] = bean.count
                    }
                    "毁型拍照" -> {
                        bean.count = data.optInt("carDismantlePhoto", 0)
                        perPoint["car_destruction_photo"] = bean.count
                    }
                }
            }
            mAdapter.notifyDataSetChanged()
        })


    }

    private fun menuBattery() {
        mBinding.mTitleText.text = "动力电池"
        mList.clear()
        //电池散件入库
        if ("power_battery_bulk_input" in mMenuList) mList.add(MenuBeanV2("散件录入", R.mipmap.p, PowerBatteryInWarehouseSingleActivity::class.java))

        if ("power_battery_bulk_in" in mMenuList) mList.add(MenuBeanV2("散件入库", R.mipmap.p, PowerConfirmInActivity::class.java))
        //电池入库单  散件入库列表
        if ("power_battery_bulk_list" in mMenuList) mList.add(MenuBeanV2("散件过磅", R.mipmap.q, PowerBatteryInWarehouseActivity::class.java, perPoint["power_battery_bulk_list"]))
        if ("power_battery_bulk_update" in mMenuList) mList.add(MenuBeanV2("散件信息补录", R.mipmap.ff, BatteryInputOtherActivity::class.java))
        //可拆解电池
        if ("power_battery_dismantle_create" in mMenuList) mList.add(MenuBeanV2("新建拆解单", R.mipmap.t, BatteryCanHandlerActivity::class.java, perPoint["power_battery_dismantle_create"]))
        //电池拆解单
        if ("power_battery_dismantle_list" in mMenuList) mList.add(MenuBeanV2("拆解单列表", R.mipmap.j, BatteryHandlerListActivity::class.java, perPoint["power_battery_dismantle_list"]))
        //电池出库 去掉了
//        if ("power_battery_create_out" in mMenuList) mList.add(MenuBeanV2("新建出库单", R.mipmap.r, BatteryCanHandlerActivity::class.java))
        //电池出库单
        if ("power_battery_out_list" in mMenuList) mList.add(MenuBeanV2("出库单列表", R.mipmap.o, PowerBatteryOutWarehouseActivity::class.java))

        if ("power_battery_query" in mMenuList) mList.add(MenuBeanV2("动力电池查询", R.mipmap.s, CarSearchActivity::class.java, searchType=1))

        if ("power_battery_apply_app" in mMenuList) mList.add(MenuBeanV2("退库申请", R.mipmap.s, ReturnApplyActivity::class.java))
        if ("power_battery_approve_app" in mMenuList) mList.add(MenuBeanV2("退库审核", R.mipmap.s, ReturnApplyActivity::class.java, searchType = 1))
        mAdapter.notifyDataSetChanged()


        ApiMethods.apiSubscribe(ApiMethods.retrofit.getPointBattery(), MyObserverHandlerLoading(this) {
            MyLog.d("回调:$it")
            val json = JSONObject(it)
            val data = json.getJSONObject("data")
            mList.forEach { bean ->
                when (bean.name) {
                    "散件过磅" -> {
                        bean.count = data.optInt("pound", 0)
                        perPoint["power_battery_bulk_list"] = bean.count
                    }
                    "新建拆解单" -> {
                        bean.count = data.optInt("detachable", 0)
                        perPoint["power_battery_dismantle_create"] = bean.count
                    }
                    "拆解单列表" -> {
                        bean.count = data.optInt("dismantle", 0)
                        perPoint["power_battery_dismantle_list"] = bean.count
                    }
                    "散件入库" -> {
                        bean.count = data.optInt("entrance", 0)
                        perPoint["power_battery_bulk_in"] = bean.count
                    }
                }
            }
            mAdapter.notifyDataSetChanged()
        })

    }

    private fun menuPart() {
        mBinding.mTitleText.text = "零部件"
        mList.clear()
        if ("parts_bulk_input" in mMenuList) mList.add(MenuBeanV2("散件录入", R.mipmap.k, PartInputActivity::class.java))
        //散件入库查询 散件入库列表
        if ("parts_bulk_list" in mMenuList) mList.add(MenuBeanV2("散件过磅", R.mipmap.l, AllPartActivity::class.java, perPoint["parts_bulk_list"]))
        //可拆配件
        if ("parts_dismantle_create" in mMenuList) mList.add(MenuBeanV2("新建拆解单", R.mipmap.bb, PartHandlerListActivity::class.java, perPoint["parts_dismantle_create"]))
        //零件拆解单
        if ("parts_dismantle_list" in mMenuList) mList.add(MenuBeanV2("拆解单列表", R.mipmap.aa, PartHandlerOverActivity::class.java, perPoint["parts_dismantle_list"]))
        //零部件出库 去掉
//        if ("parts_out_create" in mMenuList) mList.add(MenuBeanV2("新建出库单", R.mipmap.m, PartOutListActivity::class.java))
        //零部件出库单
        if ("parts_out_list" in mMenuList) mList.add(MenuBeanV2("出库单列表", R.mipmap.n, PartOutActivity::class.java))

        if ("parts_out_search_app" in mMenuList) mList.add(MenuBeanV2("散件查询", R.mipmap.t, CarSearchActivity::class.java, searchType = 2))
        mAdapter.notifyDataSetChanged()

        ApiMethods.apiSubscribe(ApiMethods.retrofit.getPointPart(), MyObserverHandlerLoading(this) {
            MyLog.d("回调:$it")
            val json = JSONObject(it)
            val data = json.getJSONObject("data")
            mList.forEach { bean ->
                when (bean.name) {
                    "散件过磅" -> {
                        bean.count = data.optInt("pound", 0)
                        perPoint["parts_bulk_list"] = bean.count
                    }
                    "新建拆解单" -> {
                        bean.count = data.optInt("detachable", 0)
                        perPoint["parts_dismantle_create"] = bean.count
                    }
                    "拆解单列表" -> {
                        bean.count = data.optInt("dismantle", 0)
                        perPoint["parts_dismantle_list"] = bean.count
                    }

                }
            }
            mAdapter.notifyDataSetChanged()
        })
    }

    private fun menuMaterial() {
        mBinding.mTitleText.text = "物料"
        mList.clear()
        if ("material_stock" in mMenuList) mList.add(MenuBeanV2("物料库存", R.mipmap.ee, MateiralWarehouseActivity::class.java))
//        mList.add(MenuBeanV2("新建出库单", R.mipmap.k, MaterialCreateActivity::class.java))
        if ("material_out_list" in mMenuList) mList.add(MenuBeanV2("出库单列表", R.mipmap.cc, MaterialListActivity::class.java))
        if ("material_out_add" in mMenuList) mList.add(MenuBeanV2("新建出库计划", R.mipmap.cc, MaterialWarehouseOutSubmitActivity::class.java))
        mAdapter.notifyDataSetChanged()
    }


    private fun menuCheck() {
        mBinding.mTitleText.text = "审批"
        mList.clear()
        if ("out_approval" in mMenuList) mList.add(MenuBeanV2("出库审批", R.mipmap.hh, OutCheckActivity::class.java, perPoint["out_approval"]))
        if ("release_approval" in mMenuList) mList.add(MenuBeanV2("放行审批", R.mipmap.ii, PassCheckActivity::class.java, perPoint["release_approval"]))
        if ("release_approval_add" in mMenuList) mList.add(MenuBeanV2("新建放行申请", R.mipmap.jj, CreatePassCheckActivity::class.java))
//        if ("material_stock" in mMenuList) mList.add(MenuBeanV2("出库确认", R.mipmap.kk, OutConfirmActivity::class.java))
        mAdapter.notifyDataSetChanged()

        ApiMethods.apiSubscribe(ApiMethods.retrofit.getPointAudit(), MyObserverHandlerLoading(this) {
            MyLog.d("回调:$it")
            val json = JSONObject(it)
            val data = json.getJSONObject("data")
            mList.forEach { bean ->
                when (bean.name) {
                    "出库审批" -> {
                        bean.count = data.optInt("out", 0)
                        perPoint["out_approval"] = bean.count
                    }
                    "放行审批" -> {
                        bean.count = data.optInt("release", 0)
                        perPoint["release_approval"] = bean.count
                    }


                }
            }
            mAdapter.notifyDataSetChanged()
        })
    }

    private val animation by lazy { AnimationUtils.loadAnimation(this, R.anim.anim_big_then_small) }
    override fun click() {
        mBinding.setting.setOnClickListener {
            startActivity<SettingActivity>()
        }

        //报废车
        mBinding.mCarLL.setOnClickListener {
            handlerFootBar(0)
        }
        //电池
        mBinding.mBatteryLL.setOnClickListener {
            handlerFootBar(1)
        }
        //零部件
        mBinding.mPartLL.setOnClickListener {
            handlerFootBar(2)
        }
        //交易
        mBinding.mMaterialLL.setOnClickListener {
            handlerFootBar(3)
        }
        //审批
        mBinding.mCheckLL.setOnClickListener {
            handlerFootBar(4)
        }
        //默认进入首页
        mBinding.mCarLL.performClick()


    }

    private var prePosition = -1
    private fun handlerFootBar(position: Int) {
        //如果点击位置依然是之前的位置则不作处理
        if (prePosition == position) {
            return
        }
        //恢复之前按钮的状态
        when (prePosition) {
            0 -> {
                mBinding.mCarTV.textColor = Color.BLACK
                mBinding.mCarIV.isSelected = false
            }
            1 -> {
                mBinding.mBatteryTV.textColor = Color.BLACK
                mBinding.mBatteryIV.isSelected = false
            }
            2 -> {
                mBinding.mPartTV.textColor = Color.BLACK
                mBinding.mPartIV.isSelected = false
            }
            3 -> {
                mBinding.mMaterialTV.textColor = Color.BLACK
                mBinding.mMaterialIV.isSelected = false
            }
            4 -> {
                mBinding.mCheckTV.textColor = Color.BLACK
                mBinding.mCheckIV.isSelected = false
            }

        }
        when (position) {
            0 -> {
                mBinding.mCarTV.textColorResource = R.color.colorAccent
                mBinding.mCarIV.startAnimation(animation)
                mBinding.mCarIV.isSelected = true
                menuCar()
            }
            1 -> {
                mBinding.mBatteryTV.textColorResource = R.color.colorAccent
                mBinding.mBatteryIV.startAnimation(animation)
                mBinding.mBatteryIV.isSelected = true
                menuBattery()
            }
            2 -> {
                mBinding.mPartTV.textColorResource = R.color.colorAccent
                mBinding.mPartIV.startAnimation(animation)
                mBinding.mPartIV.isSelected = true
                menuPart()
            }
            3 -> {
                //区分询价记录和成交订单
                mBinding.mMaterialTV.textColorResource = R.color.colorAccent
                mBinding.mMaterialIV.startAnimation(animation)
                mBinding.mMaterialIV.isSelected = true
                menuMaterial()
            }
            4 -> {
                mBinding.mCheckTV.textColorResource = R.color.colorAccent
                mBinding.mCheckIV.startAnimation(animation)
                mBinding.mCheckIV.isSelected = true
                menuCheck()
            }
        }
        prePosition = position
    }

    override fun onBackPressed() {
        exitApp()
    }

}